package com.ysm.smfu.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ysm.smfu.R;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.SharedConfig;

import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 下拉刷新listview
 * 1. listview添加刷新头
 * 2. 刷新头隐藏
 * 3. 随着手指下滑时,一起出现
 *
 * @author wangdh
 */
public class DownRefreshListView extends ListView {
    //下拉刷新,释放刷新,正在刷新
    public static final int state_down_refresh = 0;
    public static final int state_release_refresh = 1;
    public static final int state_ing_refresh = 2;
    private static final int msg_refresh_finish = 0;

    public int currentState = state_down_refresh;//当前状态:默认:下拉刷新

    private Context context;
    //刷新头布局
    //根节点
    @BindView(R.id.ll_refresh_header_root)
    LinearLayout ll_refresh_header_root;
    //刷新头所在布局
    @BindView(R.id.ll_refresh_header_view)
    RelativeLayout ll_refresh_header_view;
    //进度条
    @BindView(R.id.pb_refresh_header)
    ProgressBar pb_refresh_header;
    //箭头
    @BindView(R.id.iv_refresh_header_arrow)
    ImageView iv_refresh_header_arrow;
    //刷新头的标题:状态
    @BindView(R.id.tv_refresh_header_text)
    TextView tv_refresh_header_text;
    @BindView(R.id.tv_refresh_header_time)
    TextView tv_refresh_header_time;

    @BindView(R.id.success_refresh)
    TextView success_refresh;

    private RotateAnimation down2up;

    private RotateAnimation up2down;

    private int refreshViewHeight;

    private float downY = 0;
    private int listViewY;
    private View rollView;
    private int rollViewY;
    private OnRefresh onRefresh;
    private View rollViewTop;
    private int oriTop;
    private long lastTIme;
    private SimpleDateFormat simpleDateFormat;
    private String time;

    public DownRefreshListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        initView();
    }

    public DownRefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView();
    }

    public DownRefreshListView(Context context) {
        super(context);
        this.context = context;
        initView();
    }

    /**
     * 1. listview添加刷新头
     * 箭头旋转动画
     * 2. 刷新头隐藏
     */
    private void initView() {
        View refreshView = View.inflate(context, R.layout.refresh_header, null);
        ButterKnife.bind(this, refreshView);
        addHeaderView(refreshView);
        initAnimation();
        //完全隐藏(给paddingTop指定负的自身高度)
        ll_refresh_header_view.measure(0, 0);
        refreshViewHeight = ll_refresh_header_view.getMeasuredHeight();
        ll_refresh_header_view.setPadding(0, -refreshViewHeight, 0, 0);
        getConfig();

    }

    private void getConfig() {
        SharedPreferences sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        String name = sp.getString(SpKey.NAME, "");
        SharedPreferences currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        lastTIme = currShared.getLong(SpKey.LAST_TIME, 0);
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (lastTIme != 0) {
            time = simpleDateFormat.format(lastTIme);
        } else {
            time = simpleDateFormat.format(System.currentTimeMillis());
        }
        tv_refresh_header_time.setText(time);
    }

    /**
     * 将rollView 挂载到刷新头下面
     *
     * @param rollView
     */
    public void addCustomView(View rollView) {
        this.rollView = rollView;
        ll_refresh_header_root.addView(rollView);
    }

    /**
     * 将rollView 挂载到刷新头上面
     *
     * @param rollView
     */
    public void addCustomViewTop(View rollView) {
        rollViewTop = rollView;
        ll_refresh_header_root.addView(rollView, 0);
    }


    /**
     * 初始化旋转动画
     */
    private void initAnimation() {
        //下--上 (逆时针:旋转角度负值) 
        down2up = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        down2up.setDuration(300);
        down2up.setFillAfter(true);
        //上--下
        up2down = new RotateAnimation(-180, -360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        up2down.setDuration(300);
        up2down.setFillAfter(true);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //获取listview的位置,轮播图的位置(x,y)
        int[] location = new int[2];
        getLocationInWindow(location);
//        int listViewX = location[0];//x
        listViewY = location[1];
        //获取轮播图位置
        rollViewTop.getLocationInWindow(location);
        rollViewY = location[1];

        if (oriTop == 0)
//            赋予初始值
            oriTop = rollViewY;
        return super.dispatchTouchEvent(ev);
    }

    float upY;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        //listview可能拿不到down事件(rollviewpager将事件要回去)
        //将第一个move事件当做为down事件
//        Log.i("DownRefreshListView", "onTouchEvent:"+ev.getAction());
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
//            downY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                //如果rollViewY >= listViewY 改变刷新头的paddingTop
                if (rollViewY == oriTop) {
                    if (downY == 0) {
                        downY = ev.getY();
                        break;
                    }
                    float moveY = ev.getY();
                    float disY = moveY - downY;
                    //向下滑动时,再改变刷新头的paddingTop
                    if (disY > 0) {
                        //随着手指下滑时,一起出现
                        float paddingTop = -refreshViewHeight + disY + upY;
                        ll_refresh_header_view.setPadding(0, (int) paddingTop, 0, 0);

                        //状态切换
                        /**
                         * 1. 下拉刷新 --paddingTop>=0-- 释放刷新  (action_move)
                         2. 释放刷新 --paddingTop<0-- 下拉刷新   (action_move)
                         */
                        if (currentState == state_down_refresh && paddingTop >= 0) {
                            //下拉 -- 释放
                            currentState = state_release_refresh;
                            refreshState();
                        }
                        if (currentState == state_release_refresh && paddingTop < 0) {
                            //释放 -- 下拉
                            currentState = state_down_refresh;
                            refreshState();
                        }
                        return true;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                //手指抬起的时候,清空downY
                downY = 0;
                /**
                 * 3. 释放刷新 --松手-- 正在刷新 (action_up)

                 下拉刷新 -- 松手 -- 复原状态(完全隐藏)  (action_up)
                 */
                if (currentState == state_release_refresh || currentState == state_ing_refresh) {
                    currentState = state_ing_refresh;
                    refreshState();
                }

                if (currentState == state_down_refresh) {
                    //状态无变化  (完全隐藏)
                    ll_refresh_header_view.setPadding(0, -refreshViewHeight, 0, 0);
                    upY = 0;
                }
                break;
            default:
                break;
        }
        return super.onTouchEvent(ev);//listview响应上下滚动
    }

    /**
     * 状态发生改变,界面改变
     */
    private void refreshState() {
        switch (currentState) {
            case state_release_refresh: //下拉--释放
                //箭头向上旋转动画,文本:释放刷新
                iv_refresh_header_arrow.startAnimation(down2up);
                tv_refresh_header_text.setText("释放刷新");
                break;
            case state_down_refresh: //释放--下拉
                //箭头向下旋转动画,文本:下拉刷新
                iv_refresh_header_arrow.startAnimation(up2down);
                tv_refresh_header_text.setText("下拉刷新");
                break;
            case state_ing_refresh://释放--正在刷新
                //箭头隐藏,进度条显示,tv:正在刷新
                iv_refresh_header_arrow.setVisibility(View.GONE);
                //清空动画
                iv_refresh_header_arrow.clearAnimation();
                pb_refresh_header.setVisibility(View.VISIBLE);
                tv_refresh_header_text.setText("正在刷新");
                ll_refresh_header_view.setPadding(0, 0, 0, 0);
                upY = refreshViewHeight;
                //请求数据,刷新界面
                if (onRefresh != null)
                    onRefresh.onRefresh();
                break;

            default:
                break;
        }
    }

    /**
     * 对外提供刷新接口
     *
     * @param onRefresh
     */
    public void setOnRefresh(OnRefresh onRefresh) {
        this.onRefresh = onRefresh;
    }

    public interface OnRefresh {
        public void onRefresh();
    }

    /**
     * 设置成功刷新条数
     */
    public void setRefreshItemCount(String msg) {
        ll_refresh_header_view.setVisibility(GONE);
        success_refresh.setVisibility(VISIBLE);
        success_refresh.setText(msg);
        success_refresh.setTextColor(0x00B18F);
//        展示1秒后，回复状态
        handler.sendEmptyMessageDelayed(100, 1000);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshFinish();
        }
    };

    /**
     * 刷新完成
     */
    protected void refreshFinish() {
        //当前状态 复原
        currentState = state_down_refresh;
        //布局复原
        ll_refresh_header_view.setVisibility(VISIBLE);
        tv_refresh_header_text.setText("下拉刷新");
        success_refresh.setVisibility(GONE);
        //隐藏刷新头
        ll_refresh_header_view.setPadding(0, -refreshViewHeight, 0, 0);
        upY = 0;
//        最后刷新时间
        tv_refresh_header_time.setText(simpleDateFormat.format(System.currentTimeMillis()));
    }
}
